package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.GiftDataTO;
import com.chuantou.yuba.api.to.GiftTO;
import com.chuantou.yuba.api.to.OtherUserDataTO;
import com.chuantou.yuba.api.to.OtherUserTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.ExchangeGiftActivity;
import com.chuantou.yuba.ui.ExchangeHistoryActivity;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.ViewHolder;

/***
 * 礼包列表界面
 * 
 * @author Administrator
 * 
 */
public class GiftListFragment extends PaginationListFragment<GiftDataTO> {
	private static final int REQUEST_CODE_EXCHANGE_GIFT = 6003;
	private GiftAdapter mAdapter;
	private View mHeaderView;
	private TextView mIntegralView;
	private TextView mExchangeHistoryView;
	private AccountManager mAccountManager;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mAccountManager = AccountManager.getInstance(mContext);
		View view = super.onCreateView(inflater, container, savedInstanceState);
		if (mAdapter == null) {
			mHeaderView = inflater.inflate(R.layout.gift_list_header, null);
			mIntegralView = (TextView) mHeaderView.findViewById(R.id.integral);
			mExchangeHistoryView = (TextView) mHeaderView.findViewById(R.id.exchange_history);
			mExchangeHistoryView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(), ExchangeHistoryActivity.class);
					startActivity(intent);
				}
			});
			mListView.addHeaderView(mHeaderView);
			mListView.setHeaderDividersEnabled(true);
			mListView.setAdapter(mAdapter = new GiftAdapter());
			UserTO user = mAccountManager.getUserTO();
			setIntegral(user);
			requestProfile();
			startRequest();
		}
		return view;
	}

	private void requestProfile() {
		String url = UriHelper.getUserProfileUrl();
		final UserTO user = mAccountManager.getUserTO();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		params.put(UriHelper.PARAMS_PROF_UID, String.valueOf(user.getUid()));
		GsonRequest<OtherUserDataTO> request = new GsonRequest<OtherUserDataTO>(Method.POST, url, new Listener<OtherUserDataTO>() {

			@Override
			public void onResponse(OtherUserDataTO response) {
				if (response != null) {
					OtherUserTO profileUser = response.getUser();
					if (profileUser != null) {
						user.setIntegral(profileUser.getIntegral());
						user.setFansCount(profileUser.getFansCount());
						user.setFollowCount(profileUser.getFollowCount());
						user.setTrendsCount(profileUser.getTrendsCount());
						user.setAvatar(profileUser.getAvatar());
						AccountManager.saveUser(mContext, user);
					}
				}
				if (getActivity() != null) {
					setIntegral(user);
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, params, OtherUserDataTO.class);
		RequestManager.startRequest(mContext, request);
	}

	private void setIntegral(UserTO user) {
		int integral = user == null ? 0 : user.getIntegral();
		mIntegralView.setText(Html.fromHtml(mContext.getString(R.string.gift_integral_total, integral)));
	}

	@Override
	protected BaseGsonRequest<GiftDataTO> getRequest(Listener<GiftDataTO> listener, ErrorListener errorListener) {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		String url = UriHelper.getGiftListUrl();
		GsonRequest<GiftDataTO> request = new GsonRequest<GiftDataTO>(Method.POST, url, listener, errorListener, params, GiftDataTO.class);
		return request;
	}

	@Override
	public void onResponse(GiftDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			if (response != null) {
				List<GiftTO> gifts = response.getGifts();
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					mAdapter.clear();
				}
				mAdapter.add(gifts);
			} else {
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_content);
	}

	class GiftAdapter extends BaseAdapter {
		private List<GiftTO> mList = new ArrayList<GiftTO>();

		public void add(GiftTO to) {
			this.mList.add(to);
		}

		public void add(List<GiftTO> list) {
			if (list != null && !list.isEmpty()) {
				this.mList.addAll(list);
			}
		}

		public void clear() {
			this.mList.clear();
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.gift_list_item, null);
			}
			GiftTO gift = mList.get(position);
			NetworkImageView coverView = ViewHolder.get(convertView, R.id.cover);
			BitmapBinder.bindNetImage(mContext, coverView, gift.getCover(), R.drawable.default_image_small, false);
			TextView titleView = ViewHolder.get(convertView, R.id.title);
			titleView.setText(gift.getName());
			TextView stockView = ViewHolder.get(convertView, R.id.stock);
			stockView.setText(mContext.getString(R.string.gift_stock_format, gift.getStock()));
			TextView costView = ViewHolder.get(convertView, R.id.cost);
			costView.setText(mContext.getString(R.string.gift_cost_format, gift.getCost()));
			TextView exchangeView = ViewHolder.get(convertView, R.id.exchange);
			if (gift.getStock() > 0) {
				if (System.currentTimeMillis() / 1000 > gift.getTime()) {
					exchangeView.setEnabled(false);
					exchangeView.setText(R.string.out_of_date);
					exchangeView.setOnClickListener(null);
				} else {
					exchangeView.setEnabled(true);
					exchangeView.setText(R.string.exchange);
					exchangeView.setTag(gift);
					exchangeView.setOnClickListener(mExchangeListener);
				}
			} else {
				exchangeView.setEnabled(false);
				exchangeView.setText(R.string.out_of_stock);
				exchangeView.setOnClickListener(null);
			}
			TextView sponsorView = ViewHolder.get(convertView, R.id.sponsor);
			sponsorView.setText(mContext.getString(R.string.gift_sponsor_format, gift.getSponsor()));
			TextView timeView = ViewHolder.get(convertView, R.id.time);
			String date = DateUtil.getDateString(gift.getTime() * 1000, DateUtil.PATTERN_YMD);
			timeView.setText(mContext.getString(R.string.gift_deadline_format, date));
			return convertView;
		}
	}

	private OnClickListener mExchangeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag != null && tag instanceof GiftTO) {
				GiftTO gift = (GiftTO) tag;
				UserTO user = mAccountManager.getUserTO();
				// 提示积分不足
				int integral = user.getIntegral();
				if (integral < gift.getCost()) {
					Toast.makeText(mContext, R.string.out_of_integral, Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent(getActivity(), ExchangeGiftActivity.class);
				intent.putExtra(Constants.EXTRA_DATA, gift);
				startActivityForResult(intent, REQUEST_CODE_EXCHANGE_GIFT);
			}
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case REQUEST_CODE_EXCHANGE_GIFT:
				if (data != null) {
					GiftTO gift = data.getParcelableExtra(Constants.EXTRA_DATA);
					if (gift == null)
						return;
					UserTO user = mAccountManager.getUserTO();
					if (user != null) {
						user.setIntegral(user.getIntegral() - gift.getCost());
						setIntegral(user);
						AccountManager.saveUser(mContext, user);
						Toast.makeText(mContext, R.string.exchange_success, Toast.LENGTH_LONG).show();
					}
				}
				break;
			default:
				break;
			}
		}
	};
}
